package com.example.cms.Patients;
import com.example.cms.DB.DBUtil;
import com.example.cms.Users.User;
import java.sql.*;
import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;

public class PatientsManager {
    private Scanner scanner;
    private User currentUser;

    // 日期时间格式化器
    private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public PatientsManager() {
        this.scanner = new Scanner(System.in); // 在构造函数中初始化

    }
    // ==================== 患者管理 ====================
    public void showPatientMenu() {
        while (true) {
            System.out.println("\n--- 患者管理 ---");
            System.out.println("1. 注册新患者");
            System.out.println("2. 查看患者信息");
            System.out.println("3. 修改患者信息");
            System.out.println("4. 查看患者列表");
            System.out.println("0. 返回主菜单");

            System.out.print("请选择操作: ");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    registerPatient();
                    break;
                case "2":
                    viewPatient();
                    break;
                case "3":
                    updatePatient();
                    break;
                case "4":
                    listPatients();
                    break;
                case "0":
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void registerPatient() {
        System.out.println("\n--- 注册新患者 ---");
        try {

            System.out.print("姓名: ");
            String name = scanner.nextLine();


            System.out.print("身份证号: ");
            String idCard = scanner.nextLine();

            System.out.print("性别(M男/F女): ");
            String gender = scanner.nextLine();

            System.out.print("出生日期(YYYY-MM-DD): ");
            LocalDate birthDate = LocalDate.parse(scanner.nextLine(), dateFormatter);

            System.out.print("手机号: ");
            String phone = scanner.nextLine();

            System.out.print("地址(可选): ");
            String address = scanner.nextLine();

            System.out.print("保险类型(可选): ");
            String insuranceType = scanner.nextLine();

            Patient patient = new Patient(name, idCard, gender, birthDate, phone,address,insuranceType);
            if (!address.isEmpty()) patient.setAddress(address);
            if (!insuranceType.isEmpty()) patient.setInsuranceType(insuranceType);

            if (addPatient(patient)) {
                System.out.println("患者注册成功！");
            } else {
                System.out.println("患者注册失败！");
            }
        } catch (DateTimeParseException e) {
            System.out.println("日期格式错误，请使用 YYYY-MM-DD 格式");
        } catch (Exception e) {
            System.out.println("注册失败: " + e.getMessage());
        }
    }

    private void viewPatient() {
        System.out.println("\n--- 查看患者信息 ---");
        System.out.print("请输入患者ID: ");
        String input = scanner.nextLine();

        try {
            Patient patient = findPatientById(Integer.parseInt(input));

            if (patient != null) {
                displayPatientInfo(patient);
            } else {
                System.out.println("未找到患者信息！");
            }
        } catch (Exception e) {
            System.out.println("查询失败: " + e.getMessage());
        }
    }

    private void updatePatient() {
        System.out.println("\n--- 修改患者信息 ---");
        System.out.print("请输入患者ID: ");
        int patientId = Integer.parseInt(scanner.nextLine());

        try {
            Patient patient = findPatientById(patientId);
            if (patient == null) {
                System.out.println("患者不存在！");
                return;
            }

            displayPatientInfo(patient);
            System.out.println("\n请输入要修改的信息(留空保持不变):");

            System.out.print("姓名[" + patient.getName() + "]: ");
            String name = scanner.nextLine();
            if (!name.isEmpty()) patient.setName(name);

            System.out.print("手机号[" + patient.getPhone() + "]: ");
            String phone = scanner.nextLine();
            if (!phone.isEmpty()) patient.setPhone(phone);

            System.out.print("地址[" + patient.getAddress() + "]: ");
            String address = scanner.nextLine();
            if (!address.isEmpty()) patient.setAddress(address);

            System.out.print("保险类型[" + patient.getInsuranceType() + "]: ");
            String insuranceType = scanner.nextLine();
            if (!insuranceType.isEmpty()) patient.setInsuranceType(insuranceType);

            System.out.print("过敏史[" + patient.getAllergyHistory() + "]: ");
            String allergyHistory = scanner.nextLine();
            if (!allergyHistory.isEmpty()) patient.setAllergyHistory(allergyHistory);

            if (updatePatient(patient)) {
                System.out.println("患者信息更新成功！");
            } else {
                System.out.println("患者信息更新失败！");
            }
        } catch (Exception e) {
            System.out.println("修改失败: " + e.getMessage());
        }
    }

    private void listPatients() {
        System.out.println("\n--- 患者列表 ---");
        try {
            List<Patient> patients = getAllPatients();
            if (patients.isEmpty()) {
                System.out.println("暂无患者数据");
                return;
            }

            System.out.println("ID\t病历号\t姓名\t性别\t手机号");
            System.out.println("----------------------------------------");
            for (Patient patient : patients) {
                System.out.printf("%d\t%s\t%s\t%s\t%s\n",
                        patient.getPatientId(),
                        patient.getMedicalRecordNo(),
                        patient.getName(),
                        patient.getGender(),
                        patient.getPhone());
            }
        } catch (Exception e) {
            System.out.println("获取患者列表失败: " + e.getMessage());
        }
    }

    private Map<Integer, Patient> patients = new HashMap<>();
    private int patientIdCounter = 1;
    // 患者相关操作方法
    private boolean addPatient(Patient patient) {
        String sql = "INSERT INTO patients (medical_record_no, name, id_card, gender, birth_date, phone, address, insurance_type, allergy_history) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setString(1, patient.getMedicalRecordNo());
            pstmt.setString(2, patient.getName());
            pstmt.setString(3, patient.getIdCard());
            pstmt.setString(4, patient.getGender());
            pstmt.setDate(5, Date.valueOf(patient.getBirthDate()));
            pstmt.setString(6, patient.getPhone());
            pstmt.setString(7, patient.getAddress());
            pstmt.setString(8, patient.getInsuranceType());
            pstmt.setString(9, patient.getAllergyHistory());

            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet rs = pstmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        patient.setPatientId(rs.getInt(1));
                    }
                }
                return true;
            }
        } catch (SQLException e) {
            System.err.println("添加患者失败: " + e.getMessage());
        }
        return false;
    }

    private Patient findPatientById(int patientId) {
        String sql = "SELECT * FROM patients WHERE patient_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql))  {
            pstmt.setInt(1, patientId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return mapResultSetToPatient(rs);
                }
            }
        } catch (SQLException e) {
            System.err.println("查询患者失败: " + e.getMessage());
        }
        return null;
    }

    public Patient findPatientByUserId(int userId) {
        String sql = "SELECT p.* FROM patients p " +
                "JOIN users u ON p.name = u.name WHERE u.id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql))  {
            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return mapResultSetToPatient(rs);
                }
            }
        } catch (SQLException e) {
            System.err.println("通过用户ID查询患者失败: " + e.getMessage());
        }
        return null;
    }

    private boolean updatePatient(Patient patient) {
        String sql = "UPDATE patients SET medical_record_no = ?, name = ?, id_card = ?, gender = ?, " +
                "birth_date = ?, phone = ?, address = ?, insurance_type = ?, allergy_history = ? " +
                "WHERE patient_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, patient.getMedicalRecordNo());
            pstmt.setString(2, patient.getName());
            pstmt.setString(3, patient.getIdCard());
            pstmt.setString(4, patient.getGender());
            pstmt.setDate(5, Date.valueOf(patient.getBirthDate()));
            pstmt.setString(6, patient.getPhone());
            pstmt.setString(7, patient.getAddress());
            pstmt.setString(8, patient.getInsuranceType());
            pstmt.setString(9, patient.getAllergyHistory());
            pstmt.setInt(10, patient.getPatientId());

            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            System.err.println("更新患者失败: " + e.getMessage());
        }
        return false;
    }

    private List<Patient> getAllPatients() {
        List<Patient> patients = new ArrayList<>();
        String sql = "SELECT * FROM patients ORDER BY create_time DESC";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                patients.add(mapResultSetToPatient(rs));
            }
        } catch (SQLException e) {
            System.err.println("获取所有患者失败: " + e.getMessage());
        }
        return patients;
    }

    // ==================== 辅助方法 ====================
    private void displayPatientInfo(Patient patient) {
        System.out.println("\n=== 患者信息 ===");
        System.out.println("患者ID: " + patient.getPatientId());
        System.out.println("病历号: " + patient.getMedicalRecordNo());
        System.out.println("姓名: " + patient.getName());
        System.out.println("身份证: " + patient.getIdCard());
        System.out.println("性别: " + patient.getGender());
        System.out.println("出生日期: " + patient.getBirthDate());
        System.out.println("手机号: " + patient.getPhone());
        System.out.println("地址: " + patient.getAddress());
        System.out.println("保险类型: " + patient.getInsuranceType());
        System.out.println("过敏史: " + patient.getAllergyHistory());
        System.out.println("注册时间: " + patient.getCreateTime());
    }



    private Patient mapResultSetToPatient(ResultSet rs) throws SQLException {
        Patient patient = new Patient();
        patient.setPatientId(rs.getInt("patient_id"));
        patient.setMedicalRecordNo(rs.getString("medical_record_no"));
        patient.setName(rs.getString("name"));
        patient.setIdCard(rs.getString("id_card"));
        patient.setGender(rs.getString("gender"));
        patient.setBirthDate(rs.getDate("birth_date").toLocalDate());
        patient.setPhone(rs.getString("phone"));
        patient.setAddress(rs.getString("address"));
        patient.setInsuranceType(rs.getString("insurance_type"));
        patient.setAllergyHistory(rs.getString("allergy_history"));
        patient.setCreateTime(rs.getTimestamp("create_time").toLocalDateTime());
        return patient;
    }
    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }

}
